package com.nwpusp.transmitter.net;

import java.net.DatagramPacket;
import java.net.MulticastSocket;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.util.Log;

public class MultiSoc_Recv_Thread extends Thread{
	
	private MulticastSocket multiSoc;   
	private Timer timer;
	private TimerTask task;
	private byte inbuf[] = new byte[64]; 
	private int temp[] = new int[16];
 	private DatagramPacket inPacket = null;
 	public  List<ServerList> serverAll = new ArrayList<ServerList>();
 	private boolean newAdd = false;
 	
 	synchronized public ArrayList<ServerList> getServerAll(){
 		return (ArrayList<ServerList>) serverAll;
 	}
	
	public MultiSoc_Recv_Thread(MulticastSocket multiSoc){
		this.multiSoc = multiSoc;
		inPacket = new DatagramPacket(inbuf, 64);
		timer = new Timer();
		task = getNewTimerTask();
		timer.schedule(task,0, 100);
	}
	
	public void run(){  
        while (true){  
            try {  
            	multiSoc.receive(inPacket); 
	            for(int i=0;i<4;i++){//inPacket.getLength()
	            	temp[i] = inbuf[i];
	            	if(temp[i]<0)
	            		temp[i] += 256;
	            }
	            String tempStr  = 
	            		String.valueOf(temp[0])+"."+
	            		String.valueOf(temp[1])+"."+
	            		String.valueOf(temp[2])+"."+
	            		String.valueOf(temp[3]);
            	
	            byte nameByte[] = new byte[inPacket.getLength()-4];
	            for(int i =0;i<inPacket.getLength()-4;i++){
	            	nameByte[i] = inbuf[4+i];
	            }
	            String serverName = new String(nameByte);

	            if(serverAll.size() == 0){
	            	ServerList server = new ServerList(tempStr,serverName,temp[3]);
	            	serverAll.add(server);
	            	server.tick();
	            	}
	            	else if(serverAll.size() > 0){
	            		newAdd = true;
	            		for(ServerList server:serverAll){
	            			if(server.address.equals(tempStr)){
	            				newAdd = false;
	            				server.tick();
	            				break;
	            			}
	            		}
	            		if(newAdd){
	            			ServerList server = new ServerList(tempStr,serverName,temp[3]);
		            		serverAll.add(server);
		            		server.tick();
	            		}
	            	}
	            	
            	
            }catch (Exception e) {  
                e.printStackTrace();  

            }
             
        } 
	}
	
	public TimerTask getNewTimerTask(){
		TimerTask task = new TimerTask(){  
			public void run() { 
				for(ServerList server:serverAll){
					if(!server.isAlive){
						serverAll.remove(server);
					}
				}
			}
		}; 
		return task;
	}
	
	
}
